package com.hsgene.consumables.service.impl;

import com.hsgene.common.UsedAmont;
import com.hsgene.common.UsedType;
import com.hsgene.common.util.result.ApiResult;
import com.hsgene.common.util.result.NullObject;
import com.hsgene.common.util.support.Pagination;
import com.hsgene.consumables.condition.GoodsCondition;
import com.hsgene.consumables.domain.ConsumablesInventoryInfo;
import com.hsgene.consumables.domain.ConsumablesUnitInfo;
import com.hsgene.consumables.dto.ConsumablesInventoryInfoDto;
import com.hsgene.consumables.dto.peanut.GoodsKeywordsDto;
import com.hsgene.consumables.exception.ConsumablesErrorCode;
import com.hsgene.consumables.persistence.ConsumablesInventoryRepository;
import com.hsgene.consumables.persistence.ConsumablesUnitRepository;
import com.hsgene.consumables.service.ConsumablesInventoryService;
import com.hsgene.consumables.service.ConsumablesUnitService;
import com.hsgene.consumables.service.api.GeneratorService;
import com.hsgene.generator.dto.GeneratorDto;
import com.hsgene.product.domain.GeneticCommodityCategory;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 库存管理service
 *
 * @author wxf
 * @date 2018/8/15 8:55
 **/
@Service
public class ConsumablesInventoryServiceImpl implements ConsumablesInventoryService {

    @Resource
    private ConsumablesInventoryRepository inventoryRepository;

    @Resource
    private GeneratorService generatorService;
    @Resource
    private ConsumablesUnitRepository unitRepository;
    @Resource
    private ConsumablesUnitService consumablesUnitService;

    /**
     * 增加库存耗材名称
     *
     * @param inventoryInfo
     * @return
     */

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public int addInventoryInfo(ConsumablesInventoryInfo inventoryInfo) {
        //id
        ApiResult<GeneratorDto> generatorResult = generatorService.generate("default", null);
        if (!generatorResult.isSucc()) {
            return 0;
        }
        Date date = new Date();
        inventoryInfo.setCreateDateTime(date);
        inventoryInfo.setUpdateDateTime(date);
        inventoryInfo.setId(generatorResult.getData().getSerialNumber());
        inventoryInfo.setDeleteFlag(0);
        inventoryInfo.setIsUsed(UsedType.NO_USED.getCode());

        consumablesUnitService.updateAmount(inventoryInfo.getUnitId(), UsedAmont.ADD.getIdentifier());
        int insert = inventoryRepository.insertInventory(inventoryInfo);
        return insert;
    }

    /**
     * 获取列表
     *

     * @return
     */
    @Override
    public Pagination<ConsumablesInventoryInfoDto> queryInventoryInfo(@RequestBody GoodsCondition condition) {
        int totalCount =inventoryRepository.getCount(condition);
        Pagination<ConsumablesInventoryInfoDto> pagination = Pagination.newInstance(condition.getLimitHelper(), totalCount);
        if(totalCount>0){
            int rowNumber = (condition.getLimitHelper().getPage() - 1) * condition.getLimitHelper().getSize();
            List<ConsumablesInventoryInfoDto> consumablesInventoryInfoDtos = inventoryRepository.queryInventoryInfo(condition);
            for(int i=0,n=consumablesInventoryInfoDtos.size();i<n;i++){
                ConsumablesInventoryInfoDto consumablesInventoryInfoDto = consumablesInventoryInfoDtos.get(i);
                consumablesInventoryInfoDto.setNumber(rowNumber + i + 1);
            }
            pagination.setResult(consumablesInventoryInfoDtos);
        }else{
            pagination.setResult(new ArrayList<>());
        }
        return pagination;
    }

    /**
     * 删除信息
     *
     * @param id id
     * @return
     */
    @Override
    public ApiResult<ConsumablesInventoryInfoDto> deleteInventoryInfo(String id) {
        ConsumablesInventoryInfoDto inventoryDetais = inventoryRepository.getInventoryDetais(id);
        if(inventoryDetais!=null&&inventoryDetais.getIsUsed()==UsedType.USED.getCode()){
            return  ApiResult.fail(ConsumablesErrorCode.DELETE_GOODS_IS_OCCUPY);
        }
        boolean b = inventoryRepository.deleteInfo(id);
        return ApiResult.succ(inventoryDetais);
    }

    /**
     * 更新信息
     *
     * @param inventoryInfo 数据信息
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT, timeout = 36000, rollbackFor =
            Exception.class)
    public boolean updateInventoryInfo(ConsumablesInventoryInfo inventoryInfo) {
        //先校验数据是否已存在
        //result为null,则不存在，否则存在
       /* Object result = inventoryRepository.queryIsExists(inventoryInfo.getId(), inventoryInfo.getUnitId(),
                inventoryInfo.getWarningAmount());
        if (result != null) {
            return false;
        }*/
        Date date = new Date();
        ConsumablesUnitInfo consumablesUnitInfo = new ConsumablesUnitInfo();
        consumablesUnitInfo.setId(inventoryInfo.getUnitId());
        ConsumablesInventoryInfoDto byId = inventoryRepository.getInventoryDetais(inventoryInfo.getId());
        //改了单位
        if(!byId.getUnitId().equals(inventoryInfo.getUnitId())){

            consumablesUnitService.updateAmount(byId.getUnitId(),UsedAmont.REDUCE.getIdentifier());
            consumablesUnitService.updateAmount(inventoryInfo.getUnitId(),UsedAmont.ADD.getIdentifier());
        }
        inventoryInfo.setUpdateDateTime(date);
        int i = inventoryRepository.updateGoodsByPrimaryKeySelective(inventoryInfo);
        return true;
    }

    @Override
    public ConsumablesInventoryInfoDto getInventoryDetais(String id) {
        return inventoryRepository.getInventoryDetais(id);
    }

    @Override
    public ApiResult<ConsumablesInventoryInfo> deleteInventoryInfoMore(List<ConsumablesInventoryInfo> list) {
        if (list==null || list.isEmpty()) {
            return ApiResult.fail(ConsumablesErrorCode.PARAMETER_OBJECT_CANNOT_BE_EMPTY);
        }
        List<ConsumablesInventoryInfo> infos=new ArrayList<>();
        List<ConsumablesInventoryInfo> infosNoused=new ArrayList<>();
        list.stream().forEach(unit->{
            if(unit.getIsUsed()== UsedType.USED.getCode()){
                infos.add(unit);
            }else{
                infosNoused.add(unit);
            }
        });
        inventoryRepository.deleteUnitInfoMore(infosNoused);
        if(infos!=null&&infos.size()>0){
            StringBuilder stringBuilder=new StringBuilder();
            infos.stream().forEach(c-> stringBuilder.append(",").append(c.getNumber()));
            return new ApiResult(3008, "", "序号" + stringBuilder.deleteCharAt(0).toString() + "已被使用无法删除", null);
        }
        return ApiResult.succ();
    }

    @Override
    public ApiResult<List<ConsumablesInventoryInfoDto>> getInventoryInfoAll() {
        List<ConsumablesInventoryInfoDto> consumablesInventoryInfoDtos = inventoryRepository.queryInventoryInfo(null);
        return ApiResult.succ(consumablesInventoryInfoDtos);
    }

    @Override
    public ApiResult<List<ConsumablesInventoryInfoDto>> getInventoryDetaisByIds(String ids) {
        // fix[19560] 先行判断选择的id是否为空
        if (StringUtils.isBlank(ids)) {
            return ApiResult.fail(ConsumablesErrorCode.CONSUMABLES_INVENTORY_SELECTED_NONE);
        }
        String[] split = StringUtils.split(ids, ",");
        List<ConsumablesInventoryInfoDto> byIds = inventoryRepository.getByIds(split);
        return ApiResult.succ(byIds);
    }

    @Override
    public ApiResult<List<GoodsKeywordsDto>> getInventoryInfoByKeywords(String keyword) {
        GoodsCondition goodsCondition = new GoodsCondition();
        goodsCondition.setConsumablesName(keyword);
        List<ConsumablesInventoryInfoDto> consumablesInventoryInfoDtos = inventoryRepository.queryInventoryInfo(goodsCondition);
        List<GoodsKeywordsDto> collect = consumablesInventoryInfoDtos.stream().map(c -> {
            GoodsKeywordsDto goodsKeywordsDto = new GoodsKeywordsDto();
            goodsKeywordsDto.setId(c.getId());
            goodsKeywordsDto.setName(c.getName());
            goodsKeywordsDto.setStockNumber(c.getAmount());
            goodsKeywordsDto.setUnitId(c.getUnitId());
            goodsKeywordsDto.setUnitName(c.getConvertUnit());
            return goodsKeywordsDto;
        }).collect(Collectors.toList());
        return ApiResult.succ(collect);
    }

    @Override
    public ApiResult<ConsumablesInventoryInfoDto> getByGoodsName(String name) {
        ConsumablesInventoryInfoDto geneticCommodityCategory= inventoryRepository.getByGoodsName(name);
        return ApiResult.succ(geneticCommodityCategory);
    }

    @Override
    public ApiResult<ConsumablesInventoryInfoDto> getById(String id) {
        ConsumablesInventoryInfoDto consumablesInventoryInfoDto= inventoryRepository.getById(id);
        return ApiResult.succ(consumablesInventoryInfoDto);
    }
}
